package com.mrobuy.jdvc.service.impl;

import com.gavel.database.SQLExecutor;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.mrobuy.jd.api.Jos;
import com.mrobuy.type.ApplyState;
import com.mrobuy.jdvc.dao.CommonDao;
import com.mrobuy.jdvc.entity.JDAccount;
import com.mrobuy.jdvc.entity.VCProductApply;
import com.mrobuy.jdvc.service.VCProductApplyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("vcProductApplyService")
public class VCProductApplyServiceImpl implements VCProductApplyService {

    private static Logger LOG = LoggerFactory.getLogger(VCProductApplyService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private CommonDao commonDao;

    @Override
    public void applySync(JDAccount account) {


        JdClient client = new DefaultJdClient(Jos.SERVER, account.getAccess_token(),  account.getAppkey(), account.getAppsecret());

        try {
            List<VCProductApply> productApplies = Jos.productApplyFindClient(client)
                    .setBeginTime("2021-02-01")
                    .call();

            jdbcTemplate.update("update VC_PRODUCT_APPLY set ZT = 0");

            for (VCProductApply apply : productApplies) {
                VCProductApply existApply = SQLExecutor.executeQueryBean("select * from VC_PRODUCT_APPLY where APPLYID = ?", VCProductApply.class, apply.getApplyId());
                if ( existApply == null ) {
                    apply.setZt(1);
                    commonDao.insert(apply);
                } else {
                    if ( existApply.getState() != apply.getState() ) {
                        existApply.setState(apply.getState());
                        existApply.setWareId(apply.getWareId());
                        existApply.setOpinion(null);
                    }
                    if ( apply.getState() == ApplyState.STATE_302.code() ) {
                        existApply.setPriceexport("N");
                        existApply.setPriceexporttime(null);
                    }

                    existApply.setZt(1);
                    commonDao.update(existApply);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            LOG.error(e.getMessage(), e.getCause());
        }
    }
}
